# -*- coding: utf-8 -*-
##
## - Adding more error checking onto the urlretrieve.
##

import  urllib, urllib2, string, os, time,traceback,sys,socket
from    xml.dom     import minidom
from    types       import *    
from    base64      import b64encode
from    xbmc        import getLanguage

HOME_DIR        =   os.getcwd().replace(";","")+"\\"
COOKIE_DATA     =   'Q:\\UserData\\Scripts\\TorrentX_cookies.lwp'
########################## Cookie code thanks to WEnder ###############################
import cookielib
MyCookies       =   cookielib.LWPCookieJar()
COOKIEFILE      =   COOKIE_DATA
if os.path.isfile(COOKIEFILE)   :   MyCookies.load(COOKIEFILE)
Cookie_Opener   = urllib2.build_opener(urllib2.HTTPCookieProcessor(MyCookies))
urllib2.install_opener(Cookie_Opener)
#######################################################################################


def Download_URL(win,url,post,login,doData,doFile,timeout,Content=None):
    try :
        print '--Download_URL'
        win.ModFail     =   False
        WebData         =   ''
        import urllib,urllib2
        socket.setdefaulttimeout=int(timeout)
        if ( not doData ) :
            ## Got Login data..
            header  = checklogin(login)

            ## Normal code will run all the time..
            ## If post is empty then send None to stop 405 errors on PirateBay..
            if post == ''   :   post    =   None
            reqst   = urllib2.Request(url,post,headers=header)

            ## Pre Test
            print ' ** PRE **'
            print str(reqst.headers.items())

            reqst.add_header('User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3')

            ## Process only if Upload..
            if Content != None   :
                reqst.add_header('Content-type',Content)
                reqst.add_header('Content-length',str(len(post)))

            ## Post Test
            print ' ** POST **'
            print str(reqst.headers.items())

            try :
                html    =   urllib2.urlopen(reqst)
            except Exception,e :
                ###############################################################################
                ## Checking for these Errors. If found then unload/load the modules again..: ##
                ## ------------------------------------------------------------------------- ##
                ## URLError: <urlopen error (10038, 'Socket operation on non-socket')>       ##
                ## URLError: <urlopen error (10055, 'No buffer space available')>            ##
                ###############################################################################
                if ( '10038' in str(e) ) or ( '10055' in str(e) ) :
                    print '--Ooops-- Unload/Load the urllib/urllib2 modules..' 
                    del sys.modules['urllib']
                    del sys.modules['urllib2']
                    time.sleep(0.20)
                    win.ModFail    =   True
                else        :
                    print 'ERROR : '+ str(e)
                    return '',True
            WebData         = html.read()

            html.close()
            SaveCookie()
            return WebData,False
        else                    :
            fData   =   urllib.urlretrieve(url,doFile)
            print 'fData:'+ str(fData)
            if len(fData) > 0   :
                return 'Download of Data ok',False
            else                :
                return None,True
        return '',True
    except:
        traceback.print_exc()
        return '',True


def checklogin(login):
    if login != '' :
        return {'Authorization':'Basic '+ str(b64encode(login))}
    else                :
        return {}


def SaveCookie():
    try :
        print '--SaveCookie'
        MyCookies.save(COOKIEFILE)
    except:
        traceback.print_exc()


def ClearCookie(inetaddr):
    try :
        print '--ClearCookie'
        MyCookies.clear(domain=inetaddr)
    except:
        traceback.print_exc()

        
## Read A specific XML Tag report back from Azureus
def ATag(Elements,ForXml,Do='String'):
    try :
        print 'ELements:'+ str(Elements)
        Xml         =   {}
        if Do       ==  'String'    :   xmldoc      =   minidom.parseString(ForXml)
        else                        :   xmldoc      =   minidom.parse(ForXml)
        ForTag      =   xmldoc.getElementsByTagName(Elements)
        TagName     =   ForTag[0].nodeName
        TagValue    =   ForTag[0].childNodes[0].data
        xmldoc.unlink()
        return TagValue
    except  :
        traceback.print_exc() 
        return ''


def PutConfig(ForTag,ForXml):
    try:
        print '--PutConfig'
        f = open(ForXml,"wb")
        f.write('<config>\n')
        for Section in ForTag.keys()   :
            for MainTag in ForTag[Section].keys():
                f.write('<'+ Section +'>\n')
                f.write('\t<title>'+ MainTag + '</title>\n')
                for SubTag in ForTag[Section][MainTag].keys():
                    if type(ForTag[Section][MainTag][SubTag]) is DictType   :
                        for Ids in ForTag[Section][MainTag][SubTag].keys()  :
                            f.write('\t<'+ SubTag +' id=\"'+ str(Ids) +'\">'+ str(ForTag[Section][MainTag][SubTag][Ids]) +'</'+ SubTag +'>\n')
                    else                            :
                        f.write('\t<'+ SubTag +'>'+ str(ForTag[Section][MainTag][SubTag]) +'</'+ SubTag +'>\n')
                f.write('</'+ Section +'>\n')
        f.write('</config>\n')
        f.close()
    except:
        traceback.print_exc() 


def Check_Lang(LANGDIR,GUIXML):
    try:
        LANGOK          =   False   
        LANGUAGE        =   {}
        lang_exp        =   ATag('language',GUIXML,Do='File')
        if lang_exp     !=  ''  :   XBMC_LANGUAGE   =   lang_exp.lower()            
        else                    :   XBMC_LANGUAGE   =   'english'           
        print '-- lang_exp:'+ str(lang_exp)
        
        if os.path.isfile(LANGDIR + str(XBMC_LANGUAGE) + '.xml')            :      
            XBMC_LANGDIR        =   LANGDIR + str(XBMC_LANGUAGE) +'.xml'
            LANGOK              =   True
        else                                                                :   
            if os.path.isfile(LANGDIR + 'english.xml')                      :  
                XBMC_LANGDIR    =   LANGDIR + 'english.xml'
                XBMC_LANGUAGE   =   'english'
                LANGOK          =   True       
        print '-- LANGOK:'+ str(LANGOK) +'\n-- XBMC_LANGDIR:'+ str(XBMC_LANGDIR)

        if  LANGOK  == True     :                                               
            LANGOK  == False                                                    
            Lang                =   GetAllTags('language',XBMC_LANGDIR)
            
            if Lang.has_key(XBMC_LANGUAGE)                                  :   
                if Lang[XBMC_LANGUAGE].has_key('string')                    :  
                    if len(Lang[XBMC_LANGUAGE]['string'])   >   40          :   
                        LANGOK      =   True                                   
                        LANGUAGE    =   Lang[XBMC_LANGUAGE]['string']

        return LANGOK,LANGUAGE
    except:
        traceback.print_exc() 
        return False,{}


def GetAllTags(Elements,ForXml,Root='title',Type='default'):
    try:
        Xml =   {}
        xmldoc = minidom.parse(ForXml)
        ForTag = xmldoc.getElementsByTagName(Elements)
        for Elements in ForTag:
            XML     =   []   ;   TagName     = ''    ;   TagValue    = ''   ; root_name = ''  
            for Tag in Elements.childNodes          :
                if Tag.nodeType == Tag.ELEMENT_NODE :
                    TagAtts     = -1
                    TagName     = Tag.nodeName  
                    if len(Tag.attributes) >  0     :   TagAtts     = int(Tag.attributes["id"].value)   
                    if len(Tag.childNodes) != 0     :   TagValue    = Tag.childNodes[0].data
                    else                            :   TagValue    = ''
                    if TagAtts  != -1               :   XML.append([TagName,TagValue,TagAtts])
                    else                            :
                        if TagName == Root          :   root_name   = TagValue
                        else                        :   XML.append([TagName,TagValue])
            if not Xml.has_key(root_name)           :   Xml[root_name]  =   {}
            for items in XML        :
                if len(items) == 2  :
                    if Type == 'default'    :   Xml[root_name][items[0]]    =   items[1]
                    else                    :
                        if not Xml[root_name].has_key(items[0]) :
                            Xml[root_name][items[0]]    =   []
                        Xml[root_name][items[0]].append(items[1])
                else                :
                    if not Xml[root_name].has_key(items[0])  :
                        Xml[root_name][items[0]]  =   {}
                    Xml[root_name][items[0]][items[2]]  =   items[1]
                
        xmldoc.unlink()
        return Xml
    except:
        traceback.print_exc() 
        return {}
